package com.xiaoq.shop.repository.impl;

import com.mongodb.WriteConcern;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.shop.entity.CouponEntity;
import com.xiaoq.shop.repository.ICouponRepository;
import com.xiaoq.vo.PagingVo;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.mongodb.morphia.query.UpdateResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class CouponRepositoryImpl implements ICouponRepository {

    @Autowired
    private Datastore dataStore;

    /**
     * 根据根据ID，查询已生效优惠券列表
     * @param shopId 店（景区）ID
     * @param expireDate 小于expireDate时间
     * @return
     */
    public List<CouponEntity> getAllCouponList(String shopId, Long expireDate){
        if(StringUtils.isBlank(shopId)){
            return new ArrayList<>();
        }
        Query<CouponEntity> couponEntityQuery = dataStore.find(CouponEntity.class)
                .field("shopId").equal(shopId)
                .field("delete").equal(0) //正常的优惠券
                .field("state").equal(ConstantUtil.COUPON_SALE_ON);
        if(expireDate != null){
            couponEntityQuery.field("expirationDate").greaterThan(expireDate.longValue());
            couponEntityQuery.field("effectiveDate").lessThan(expireDate.longValue());
        }

        couponEntityQuery.order("-expirationDate");
        return couponEntityQuery.asList();
    }

    @Override
    public CouponEntity getCoupon(String couponId) {
        if(StringUtils.isBlank(couponId)){
            return null;
        }
        Query<CouponEntity> couponEntityQuery = dataStore.find(CouponEntity.class)
                .field("_id").equal(couponId)
                .field("delete").equal(0); //正常的优惠券

        return couponEntityQuery.get();
    }

    @Override
    public boolean save(CouponEntity couponEntity) {
        if(couponEntity==null || StringUtils.isBlank(couponEntity.getId())){
            return false;
        }

        dataStore.save(couponEntity);
        return true;
    }

    @Override
    public boolean update(CouponEntity couponEntity) {
        if(couponEntity==null || StringUtils.isBlank(couponEntity.getId())){
            return false;
        }

        Query<CouponEntity> couponEntityQuery = dataStore.find(CouponEntity.class)
                .field("_id").equal(couponEntity.getId());
        if(StringUtils.isNotBlank(couponEntity.getShopId())){
            couponEntityQuery.filter("shopId", couponEntity.getShopId());
        }

        UpdateOperations<CouponEntity> ops = dataStore.createUpdateOperations(CouponEntity.class);
        if(StringUtils.isNotBlank(couponEntity.getDescription())){
            ops.set("description", couponEntity.getDescription());
        }
        if(StringUtils.isNotBlank(couponEntity.getExtension())){
            ops.set("extension", couponEntity.getExtension());
        }
        if(StringUtils.isNotBlank(couponEntity.getShopName())){
            ops.set("shopName", couponEntity.getShopName());
        }
        if(StringUtils.isNotBlank(couponEntity.getTitle())){
            ops.set("title", couponEntity.getTitle());
        }
        if(couponEntity.getCount() != null){
            ops.set("count", couponEntity.getCount());
        }
        if(couponEntity.getCouponTemplateCode() != null){
            ops.set("couponTemplateCode", couponEntity.getCouponTemplateCode());
        }
        if(couponEntity.getEffectiveDate() != null){
            ops.set("effectiveDate", couponEntity.getEffectiveDate());
        }
        if(couponEntity.getLimitCount() != null){
            ops.set("limitCount", couponEntity.getLimitCount());
        }
        if(couponEntity.getNotify() != null){
            ops.set("notify", couponEntity.getNotify());
        }
        if(couponEntity.getDenomination() != null){
            ops.set("denomination", couponEntity.getDenomination());
        }
        if(couponEntity.getExpirationDate() != null){
            ops.set("expirationDate", couponEntity.getExpirationDate());
        }
        if(couponEntity.getMinSpendingAmountForUse() != null){
            ops.set("minSpendingAmountForUse", couponEntity.getMinSpendingAmountForUse());
        }
        if(couponEntity.getDelete() != null){
            ops.set("delete", couponEntity.getDelete());
        }
        if(couponEntity.getState() != null){
            ops.set("state", couponEntity.getState());
        }
        if(couponEntity.getUnconditional() != null){
            ops.set("unconditional", couponEntity.getUnconditional());
        }

        ops.set("updatedAt", System.currentTimeMillis());
        dataStore.update(couponEntityQuery, ops);
        return true;
    }

    @Override
    public boolean incTakenCountPlus1(String couponId) {
        if(StringUtils.isBlank(couponId)){
            return false;
        }
        Query<CouponEntity> couponEntityQuery = dataStore.find(CouponEntity.class)
                .field("_id").equal(couponId);
        UpdateOperations<CouponEntity> ops = dataStore.createUpdateOperations(CouponEntity.class).inc("takenCount");
        UpdateResults updateResults = dataStore.update(couponEntityQuery, ops,false, WriteConcern.ACKNOWLEDGED);
        return updateResults.getUpdatedExisting();
    }


    /**
     * 分页查询优惠券信息
     * @param shopId 景区id
     * @param type all,wait,start,end 4种类型
     * @param pagingVo 分页
     * @return
     */
    @Override
    public List<CouponEntity> getAllCouponList(String shopId, String type, PagingVo pagingVo) {
        if(StringUtils.isBlank(shopId)){
            return new ArrayList<>();
        }
        long currentMillis = System.currentTimeMillis();
        Query<CouponEntity> query = dataStore.createQuery(CouponEntity.class)
                .filter("shopId", shopId)
                .order("-createdAt");

        if("all".equals(type)){
//            query.filter()
        }else if("wait".equals(type)){
            query.filter("effectiveDate >", currentMillis);
        }else if("start".equals(type)){
            query.filter("effectiveDate <", currentMillis)
                .filter("expirationDate >", currentMillis);
        }else if("end".equals(type)){
            query.filter("expirationDate <", currentMillis);
        }
        if(pagingVo != null){
            query.offset(pagingVo.getPageOffset()).limit(pagingVo.getPs());
        }

        return query.asList();
    }

    @Override
    public long getAllCouponListCount(String shopId, String type) {
        if(StringUtils.isBlank(shopId)){
            return 0L;
        }
        long currentMillis = System.currentTimeMillis();
        Query<CouponEntity> query = dataStore.createQuery(CouponEntity.class)
                .filter("shopId", shopId);

        if("all".equals(type)){
//            query.filter()
        }else if("wait".equals(type)){
            query.filter("effectiveDate >", currentMillis);
        }else if("start".equals(type)){
            query.filter("effectiveDate <", currentMillis)
                    .filter("expirationDate >", currentMillis);
        }else if("end".equals(type)){
            query.filter("expirationDate <", currentMillis);
        }
        return query.count();
    }

    @Override
    public List<CouponEntity> getAllCoupon4NotifyNotExpired(Integer notify) {
        Query<CouponEntity> query = dataStore.createQuery(CouponEntity.class)
                .filter("expirationDate > ", System.currentTimeMillis());
        if(notify != null){
            query.filter("notify = ", notify);
        }
        return query.asList();
    }
}
